using BootstrapBlazor.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WorkSystem.Extensinos
{
    public   class TableExtensinos
    {  

    public async Task<QueryData<TModel>> QueryTable<TModel>(QueryPageOptions option, IQueryable<TModel> model) where TModel : class, new()
    {
        var ret = new QueryData<TModel>
        {
            IsSorted = true,
            IsFiltered = true,
            IsSearch = true,
            IsAdvanceSearch = true
        };

        var filter = option.ToFilter();

        if (option.IsPage)
        {
            var pagedItems = model.AsQueryable()
                                .Where(filter.GetFilterLambda<TModel>(), filter.HasFilters())
                                .Sort(option.SortName!, option.SortOrder, !string.IsNullOrEmpty(option.SortName))
                                .Count(out var count)
                                .Page((option.PageIndex - 1) * option.PageItems, option.PageItems);

            ret.TotalCount = count;
            ret.Items = pagedItems;
        }
        else
        {
            var sortedItems = model.AsQueryable()
                                .Where(filter.GetFilterLambda<TModel>(), filter.HasFilters())
                                .Sort(option.SortName!, option.SortOrder, !string.IsNullOrEmpty(option.SortName))
                                .Count(out var count);

            ret.TotalCount = count;
            ret.Items = sortedItems;
        }

        return ret;
    }

    }
}